﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.DataModel;
using System.Net;
using System.IO;

namespace Tracy.Plugins.DownloadAdapters
{
    public class MonoTorrentAdapter : IDownloadAdapter
    {
        MonoTorrent.Client.ClientEngine _engine;
        FormBTMonitor _formMonitor;
        
        public MonoTorrentAdapter()
        {
            _engine = new MonoTorrent.Client.ClientEngine(new MonoTorrent.Client.EngineSettings());
            _formMonitor = new FormBTMonitor();
            
        }

        public void Download(Resource res, string defaultPath, bool autoMode)
        {
            string tempFile = Path.GetTempPath() + res.GetFileName();
            WebClient client = new WebClient();
            client.DownloadFile(res.Url, tempFile);
            MonoTorrent.Common.Torrent torrent = MonoTorrent.Common.Torrent.Load(tempFile);
            MonoTorrent.Client.TorrentManager manager = new MonoTorrent.Client.TorrentManager(torrent, defaultPath, new MonoTorrent.Client.TorrentSettings());
            _engine.Register(manager);
            manager.Start();

            _formMonitor.AddTask(manager);
        }

        public void DisplayUI()
        {
            if (!_formMonitor.Visible) _formMonitor.Show();
            else _formMonitor.Hide();
        }

        public bool IsAvailable()
        {
            return true;
        }

        public bool IsResourceTypeSupported(string type)
        {
            if (IsAvailable())
            {
                if (type == "BT") return true;
            }
            return false;
        }

        public string[] GetTempFileExts(string type)
        {
            return new string[] { ".bt" };
        }

        public string GetTempDownloadFolder(string preferredFolder)
        {
            return preferredFolder;
        }

        public string GetValidFileName(string fileName)
        {
            if (fileName == null) return null;
            return fileName.Replace("?", "_").Replace("\\", "_").Replace("/", "_").Replace("*", "_").Replace("\"", "_").Replace(":", "_").Replace("<", "_").Replace(">", "_");
        }
    }
}
